<template>
  <view class="userinfo-form-item-input-wrapper" @tap="open">
    <view class="userinfo-form-item-input">
      <view v-if="showPlacholder">{{ current_value }}</view>
      <view v-else class="userinfo-form-item-input-placeholder">{{ placeholder }}</view>
    </view>
    <view class="userinfo-form-item-arrow">
      <img src="/employee/img/arrow.png" alt />
    </view>
    <lb-picker
      ref="picker"
      :value="value"
      :list="areaList"
      :level="2"
      mode="multiSelector"
      @confirm="onConfirm"
    />
  </view>
</template>
<script>
import { mapGetters } from "vuex";
import LbPicker from "./lb-picker";
export default {
  name: "",
  components: {
    LbPicker
  },
  props: {
    defaultValue: {
      type: [String, Number],
      default: 0
    },
    level: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      placeholder: "请选择",
      current_value: "",
      value: []
    };
  },
  computed: {
    ...mapGetters(["areaList", "areaSourceList"]),
    showPlacholder() {
      return this.current_value && this.current_value.length > 0;
    }
  },

  watch: {
    defaultValue(val) {
      this.value = this.buildValue(val);
      this.current_value = this.value
        .map(
          item => this.areaSourceList.filter(it => it.id === item)[0]["name"]
        )
        .join("-");
    }
  },
  created() {
    this.value = this.buildValue(this.defaultValue);
    this.current_value = this.value
      .map(item => this.areaSourceList.filter(it => it.id === item)[0]["name"])
      .join("-");
  },
  methods: {
    onConfirm(res) {
      this.current_value = res.item.map(item => item.label).join("-");
      const obj = {
        value: res.value,
        label: res.item.map(item => item.label),
        item: res.item
      };
      this.$emit("input", obj);
      this.$emit("change", obj);
    },
    open() {
      this.$refs.picker.show();
    },
    buildValue(id) {
      id = parseInt(id);
      const index = this.areaSourceList.findIndex(
        item => item.id === parseInt(id)
      );
      if (index > -1) {
        const item = this.areaSourceList[index];
        if (item.parentId > 0) {
          return this.buildValue(item.parentId).concat([id]);
        } else {
          return [id];
        }
      } else {
        return [];
      }
    }
  }
};
</script>
